from .views import *

# 用户对应角色管理
class UserCharacterAdmin(APIView):
    def get(self, request):
        res = {}
        uid = request.GET.get('uid')
        if uid:
            uid = int(uid)
        else:
            uid = getID(request)
        user = User.objects.get(id= uid)
        user = UserSer(user)
        res['code'] = 200
        res['data'] = user.data.get('character')
        return Response(res)
    def post(self, request):
        res = {}
        uid = request.data.get('uid')
        character_id_list = request.data.get('character_id_list')
        u_datas = User.objects.get(id=uid)
        characters = UserSer(u_datas).data.get('character')
        already_character_list = []
        for i in characters:
            already_character_list.append(i.get('id'))
            if not i.get('id') in character_id_list:
                u_datas.character.remove(Character.objects.get(id=i['id']))
        for j in character_id_list:
            # 如果rights里没有该id，则添加
            if not j in already_character_list:
                u_datas.character.add(Character.objects.get(id=j))
        # 修改信息
        u_datas.save()
        res['code'] = 200
        res['message'] = '操作成功'
        return Response(res)


# 角色对应权限管理
class CharacterRightAdmin(APIView):
    # 查询当前用户有哪些权限
    def get(self, request):
        res = {}
        character_id = request.GET.get('character_id')
        c_datas = Character.objects.get(id=character_id)
        res['code'] = 200
        res['data'] = CharacterSer(c_datas).data.get('right')
        return Response(res)
    def post(self, request):
        res = {}
        character_id = request.data.get('character_id')
        right_id_list = request.data.get('right_id_list')
        c_datas = Character.objects.get(id=character_id)
        rights = CharacterSer(c_datas).data.get('right')
        already_right_list = []
        for i in rights:
            # 如果r表里有，则不变，如果r表里没有，则删除
            already_right_list.append(i.get('id'))
            if not  i.get('id') in right_id_list:
                c_datas.right.remove(Right.objects.get(id=i['id']))
        for j in right_id_list:
            # 如果rights里没有该id，则添加
            if not j in already_right_list:
                c_datas.right.add(Right.objects.get(id=j))
        # 修改信息
        c_datas.save()
        res['code'] = 200
        res['message'] = '操作成功'
        return Response(res)


# 权限认证
class RightJudge(APIView):
    def get(self, request):
        res = {}
        id = getID(request)
        character = User.objects.get(id= id).character
        url = request.GET.get('url')
        modal = request.GET.get('modal')
        # 序列化
        c_data = CharacterSer(character, many=True).data
        # 超级管理员可以随意访问
        for i in c_data:
            if i.get('id') == 1:
                print('你是超级管理员')
                res['data'] = True
                return Response(res)
            for j in i.get('right'):
                if j.get('url'):
                    if url == j.get('url'):
                        res['data'] = True
                        return Response(res)

                if j.get('modal'):
                    if modal == j.get('modal'):
                        res['data'] = True
                        return Response(res)
        res['data'] = False
        return Response(res)

# 权限管理
# 已排重
class RightAdmin(APIView):
    def get(self, request):
        uid = getID(request)
        user = User.objects.get(id= uid)
        character = user.character
        c_data = CharacterSer(character, many=True).data
        is_super = False
        for c in c_data:
            if c['id'] == 1:
                is_super = True
        res = {}
        if is_super:
            rights = Right.objects.all()
        else:
            rights = Right.objects.filter(givable= 1)
        res['code'] = 200
        res['data'] = RightSer(rights, many=True).data
        return Response(res)

    def post(self, request):
        # 改功能只能由超级管理员添加
        res = {}
        url = request.data.get('url')
        modal = request.data.get('modal')
        desc = request.data.get('desc')
        if url:
            u = Right.objects.filter(url= url)
            if u:
                res['code'] = 403
                res['message'] = '路由重复'
                return Response(res)
        if modal:
            m = Right.objects.filter(modal= modal)
            if m:
                res['code'] = 403
                res['message'] = '模块重复'
                return Response(res)
        if desc:
            m = Right.objects.filter(desc= desc)
            if m:
                res['code'] = 403
                res['message'] = '描述重复'
                return Response(res)
        else:
            res['code'] = 403
            res['message'] = '缺少描述'
            return Response(res)

        if url or modal:

            Right(url= url, modal= modal, desc=desc).save()

            res['code'] = 200
            res['message'] = '添加成功'

        else:
            paramsError(res)
        return Response(res)

# 角色管理
# 已排重
class CharacterAdmin(APIView):
    def get(self, request):
        res = {}
        uid = getID(request)
        office = User.objects.get(id=uid).office

        if 1 in getRights(request):
            data = Character.objects.all()
        else:
            data = Character.objects.filter(office= office)
        res['code'] = 200
        res['data'] = CharacterSer(data, many=True).data
        return Response(res)
    # 添加角色
    def post(self, request):
        res = {}
        character = request.data.get('character')
        oid = request.data.get('office_id')
        # 查重
        c = Character.objects.filter(character= character).filter(Q(office_id=oid) | Q(office_id=None))
        if c:
            res['data'] = 403
            res['message'] = '该角色已存在'
            return Response(res)
        # 入库
        if oid == 0:
            Character(character=character).save()
        else:
            Character(character=character, office_id=oid).save()
        res['data'] = 200
        res['message'] = '操作成功'
        return Response(res)


class Reg(APIView):
    def post(self, request):
        res = {}

        user = request.data
        username = user.get('username')
        password = user.get('password')
        phone = user.get('phone')
        photo = user.get('photo', 'avatar.jpg')
        oid = user.get('oid', 1)
        code = request.data.get('code', None)  # 验证码
        if  5 < len(username) < 17 and 7 < len(password) < 17 and len(phone) == 11:

            User.objects.create_user(username=username, password=password, phone=phone, photo= photo, office_id= oid)
            res['code'] = 200
            res['message'] =  '注册成功'

        else:
            res['code'] = 403
            res['message'] = '参数错误'

        return Response(res)


class Login(APIView):

    def post(self, request):
        res = {}
        # 获取用户名
        username = request.data.get('username', 'null')
        # 获取密码
        password = request.data.get('password', 'null')
        # 验证信息是否正确
        try:
            user = authenticate(username=username, password=password)

            # 如果信息正确
            if user:
                # 生成jwt
                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                # 写入最后登陆时间
                user.last_login = timezone.now()
                user.save()
                res['code'] = 200
                res['message'] = "登陆成功"
                res['username'] = user.username
                res['uid'] = user.id
                res['jwt'] = token
                res['img'] = user.photo


                return Response(res)

        except:
            # 如果错误
            res['code'] = 403
            res['message'] = "信息错误"
            return Response(res)
        paramsError(res)
        return Response(res)

# 公司管理
# 已排重
class OfficeAdmin(APIView):
    def get(self, request):
        res = {}
        # 解密
        try:
            uid = getID(request)
            # #获取权限
            if 1 in getRights(request):
                office = Office.objects.all()
            else:
                office = [User.objects.get(id= uid).office]
            res['data'] = OfficeSer(office, many=True).data
            res['code'] = 200
            print(res)
        except:
            paramsError(res)
        return Response(res)
    def post(self, request):
        # 添加公司
        res = {}
        data = request.data
        office = data.get('office')
        city = data.get('city')
        street = data.get('street')
        img = data.get('img')
        # 排重
        if Office.objects.filter(office=request.data.get('office')):
            res['code'] = 403
            res['message'] = '公司名已存在'
            return Response(res)

        try:
            Office(office= office, city=city, street= street, img= img).save()
            res['code'] = 200
            res['message'] = '添加成功'
        except:
            paramsError(res)
        return Response(res)

# 用户管理
# 已排重
class UserAdmin(APIView):
    def get(self, request):
        res = {}
        try:
            uid = getID(request)
            office = User.objects.get(id=uid).office
            # 获取权限，如果没有全局访问，则只展示本公司的用户
            if 1 in getRights(request):
                user_list = User.objects.all()
            else:
                user_list = User.objects.filter(office=office)
            # 序列化
            data = UserSer(user_list, many=True).data
            res['data'] = data
            res['code'] = 200
        except:
            paramsError(res)
        return Response(res)
    # 添加用户
    def post(self, request):
        res = {}

        user = request.data
        username = user.get('username')
        password = user.get('pass')
        phone = user.get('phone')
        photo = user.get('img', 'avatar.jpg')
        oid = user.get('oid', 1)
        email = user.get('email')
        # 排重
        if User.objects.filter(username= username):
            res['code'] = 403
            res['message'] = '用户名已存在'
            return Response(res)
        if  5 < len(username) < 17 and 7 < len(password) < 17 and len(phone) == 11:
            User.objects.create_user(
                username=username,
                password=password,
                phone=phone,
                photo= photo,
                office = Office.objects.get(id= oid),
                email = email
            )
            res['code'] = 200
            res['message'] =  '添加成功'

        else:
            res['code'] = 403
            res['message'] = '参数错误'

        return Response(res)



# 用来测试封装的方法
class TestFunc(APIView):
    def get(self, request):
        res = []
        return Response(res)


